管線(或管道)應用在 Linux 中是匿名管道的其中一種,屬於單向流。我們可以把每個程式的訊息輸出視為水流,使用水管把這些水流導到另一個程式,這就是管線的概念。
從先前的練習中我們已經知道每個行程都會有 stdin、stdout 與 stderr 等訊息輸入與輸出流,而每個行程的 stdin 可以是前一個行程的輸出,這個輸出必須是 stdout 才行。
若要把行程的 stdout 交給另一程式的 stdin 做後續處理,那麼我們可以使用管導 (PIPE) 符號 | 進行連接,如下圖所示。
| 將 STDOUT 透過 pipe 導到下一程式 |
|---|
![]() |
我們使用 ls -l 檢視 sample 檔案後,透過 | 傳給 grep 找出 sample 字串:
student$ ls -lh sample | grep sample --color
-rw-r--r-- 1 student student 1.8K Aug 25 16:44 sample
在上面的輸出中,我們會看到 sample 字串有紅色字樣,這個紅色字樣是由 grep 所套用。
透過下列的方式,我們刻意列出不存在的 sample2 進行測試,再看看是否能被 grep 接收到:
student$ ls -lh sample2 | grep sample --color
ls: cannot access sample2: No such file or directory
在上面的輸出結果中可以看到沒有任何字串有紅色字樣,代表這個訊息沒有流到 grep 中。
從上面的輸出我們得到幾個重點:
stderr 的情況時,那麼整個流程會停在有問題的階段,不會再繼續處理。若我們需要把 stderr 的訊息也透過 pipe 傳到下一行程的話,可以使用下列方法:
student$ ls -lh sample2 2>&1 | grep sample --color
ls: cannot access sample2: No such file or directory
透過如訊息重導的技巧,就可以把原本流到 stderr 的方向全部轉到 stdout,此時就可以看到 sample2 的 sample 字被套入紅色字樣。